import * as Qs from "qs";
import { message } from 'antd';
import comm from "src/config/comm";
const myHeaders = new Headers();
myHeaders.append("content-type",'application/json'); // 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
myHeaders.append("Accept","application/json");


function checked(response:any){
    if(response.ok) {
        return response.json().then((res:any)=>{
            if(res.code === 200){
                return Promise.resolve(res.data);
            }else if(res.code === 1003){
                if(response.url.indexOf("_quite=1") === -1){
                    message.warning(res.msg || "登录信息过期,请重新登录").then(()=>{
                        comm.toLogin();
                    },(err:any)=>{
                        console.warn(err);
                    });
                    return Promise.reject(res);
                }else{
                    return Promise.reject(null);
                }
                // alert
                
            }else{
                message.warning(res.msg || "服务器错误");
                return Promise.reject(res);
            }
        });
    }else{
        // alert
        message.error("网络错误");
        return Promise.reject("网络错误");
    }
}

export default {
    post(url:string,data?:object){
        return fetch(url, {
            body: JSON.stringify(data), // must match 'Content-Type' header
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'include', // include, same-origin, *omit
            headers: myHeaders,
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, cors, *same-origin
            redirect: 'follow', // manual, *follow, error
            referrer: 'no-referrer', // *client, no-referrer
          })
          .then(checked) // parses response to JSON
    },
    get(url:string,data?:object){
        if(data){
            const params = Qs.stringify(data);
            if(url.search(/\?/) === -1){
                url += '?' + params;
            }else{
                url += '&' + params;
            }
        }
        return fetch(url, {
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'include', // include, same-origin, *omit
            headers: myHeaders,
            method: 'GET', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, cors, *same-origin
            redirect: 'follow', // manual, *follow, error
            referrer: 'no-referrer', // *client, no-referrer
          })
          .then(checked) // parses response to JSON
    },
    file(url:string,formData:FormData){
        return fetch(url, {
            method: 'POST',
            body: formData
          })
          .then(checked)
    }
}